package com.qfmy.app.service.impl.community;

import com.qfmy.app.mapper.community.BolgCommentMapper;
import com.qfmy.app.service.community.BlogCommentService;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.community.BlogComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.community
 * @date 2025/4/17
 * @description 博客评论
 */
@Service
@SuppressWarnings("all")
public class BlogCommentServiceImpl implements BlogCommentService {
    /**
     * 博客评论
     */
    @Autowired
    private BolgCommentMapper blogCommentMapper;

    /**
     * 添加博客评论
     * @param blogId
     * @param content
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBlogComment(Integer blogId, String content) {
        //获取用户id
        Integer userId = getUserId();
        //创建博客评论
        BlogComment blogComment = new BlogComment();
        blogComment.setUserId(userId);
        blogComment.setBlogId(blogId);
        blogComment.setContent(content);
        blogCommentMapper.insert(blogComment);
    }

    /**
     * 获取博客评论
     * @param pageNum
     * @param size
     * @param blogId
     * @return
     */
    @Override
    public List<BlogComment> getBlogComment(Integer pageNum, Integer size, Integer blogId) {
        //计算分页
        int start = getStart(pageNum, size);
        //获取博客评论
        List<BlogComment> blogComments = blogCommentMapper.getBlogComment(start, size, blogId);
        return blogComments;
    }

    /**
     * 计算分页
     * @param pageNum
     * @param size
     * @return
     */
    private int getStart(Integer pageNum, Integer size) {
        pageNum = Math.max(pageNum, 1);
        size = Math.max(size, 25);
        return  (pageNum - 1) * size;
    }

    /**
     * 获取用户id
     * @return
     */
    private Integer getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        Integer userId = loginUser.getUserId();
        return userId;
    }
}
